import os
import pika
import redis
import json
import threading
import time
import signal


def loadjson(jsonfile):
    with open(jsonfile) as json_file:
        data = json.load(json_file)
        return data


conf = loadjson(os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json"))

cd = True
seconds = conf['seconds']


def countdown():
    global seconds, cd
    while seconds > 0:
        if cd:
            print(seconds)
            seconds -= 1
        time.sleep(1)
    pid = os.getpid()
    os.kill(pid, signal.SIGTERM)


def callback(ch, method, properties, body):
    global seconds, cd
    cd = False
    data = json.loads(body.decode('UTF-8'))
    print(data)
    shell = r.get(data["body"])

    import subprocess
    proc = subprocess.Popen(shell, shell=True, stdout=subprocess.PIPE)
    stdout_value = proc.communicate()[0]

    print(stdout_value.decode())
    ch.basic_ack(delivery_tag=method.delivery_tag)
    seconds = conf['seconds']
    cd = True


if __name__ == '__main__':
    host_name = os.uname()[1]

    r = redis.Redis(host=conf['redis']['host'], port=conf['redis']['port'], db=0)
    user_pwd = pika.PlainCredentials(conf['rabbitmq']['username'], conf['rabbitmq']['password'])
    s_conn = pika.BlockingConnection(
        pika.ConnectionParameters(conf['rabbitmq']['host'], credentials=user_pwd, heartbeat=0))
    chan = s_conn.channel()
    chan.queue_declare(queue=host_name, durable=True)
    chan.basic_qos(prefetch_count=1)
    chan.basic_consume(queue=host_name, on_message_callback=callback, auto_ack=False)

    thread = threading.Thread(target=countdown)
    thread.start()
    chan.start_consuming()
